﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using NDK.Utils;
using NDK.Module.Model;
using System.Threading;

namespace NDK.Frm
{
    public partial class ROIComapreForm : Form
    {
        public DataTable ngDt = new DataTable();
        DataTable roiTable = new DataTable();

        Thread threadCommpare = null;

        /// <summary>
        /// 窗体对象实例，单例模式,保证整个工程只有一个实例
        /// </summary>
        private static ROIComapreForm _instance;
        private static readonly object singletonLock = new object();
        public static ROIComapreForm Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new ROIComapreForm();
                        }
                    }
                }
                return _instance;
            }
        }

        public ROIComapreForm()
        {
            InitializeComponent();

            threadCommpare = new Thread(new ThreadStart(commpaerMethod));
            threadCommpare.IsBackground = true;
            threadCommpare.Start();

            ngDt.Columns.Add("Changed Measurement", typeof(String));
            ngDt.Columns.Add("Changed Num", typeof(String));
        }

        private void ROIComapreForm_Load(object sender, EventArgs e)
        {

        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            if (ngDt != null && ngDt.Rows.Count > 0)
            {
                ngDGV.Visible = true;
                ngDGV.DataSource = ngDt.DefaultView;
            }
            else
            {
                ngDGV.Rows.Clear();
                ngDGV.Visible = false;
            }
        }

        private void commpaerMethod()
        {
            while (true)
            {
                string rootPath = "";
                if (Common.isFileSetPassCode == false)
                {
                    rootPath = FileUtils.GetAppDirectory() + @"\hdevengine\Procedures";
                }
                else
                {
                    rootPath = FileUtils.GetAppDirectory() + @"\hdevengine\Procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}";
                }

                string roi_7060 = rootPath + "\\" + "K7060_Station_Vision_ROI_New.txt";
                string roi_7060_Std = rootPath + "\\ROI_Std" + "\\" + "K7060_Station_Vision_ROI_Std.txt";

                string roiFilePath = "";
                string roiFilePath_Std = "";

                int totalNgCount_Camera = 0;
                int totalNgCount_7060 = 0;
                int totalNgCount_Gocator = 0;

                int totalNgCount_Cognex = 0;
                int totalNgCount_Spc = 0;

                if (Common.ProjectName == "Bottom")
                {
                    roiFilePath = rootPath + "\\" + "R2297_Station_Vision_Bottom_ROI_New.txt";
                    roiFilePath_Std = rootPath + "\\ROI_Std" + "\\" + "R2297_Station_Vision_Bottom_ROI_Std.txt";

                    string roi_Gocator = rootPath + "\\" + "Gocator_Station_Bottom_Vision_ROI_New.txt";
                    string roi_Gocator_Std = rootPath + "\\ROI_Std" + "\\" + "Gocator_Station_Bottom_Vision_ROI_Std.txt";



                    CompareRoiFuc(roiFilePath, roiFilePath_Std, ref totalNgCount_Camera);
                    CompareRoiFuc(roi_7060, roi_7060_Std, ref totalNgCount_7060);
                    CompareRoiFuc(roi_Gocator, roi_Gocator_Std, ref totalNgCount_Gocator);
                }
                else if (Common.ProjectName == "Book")
                {
                    #region 2D Camera Compare
                    roiFilePath = rootPath + "\\" + "R2297_Station_Vision_Book_ROI_New.txt";
                    roiFilePath_Std = rootPath +  "\\" + "R2297_Station_Vision_Book_ROI_New_Std.txt";
                    CompareRoiFuc(roiFilePath, roiFilePath_Std, ref totalNgCount_Camera);
                    #endregion

                    #region Cognex Laser Compare
                    string CognexRoiPath = FileUtils.GetAppDirectory() + @"\DN\RunConfig.ini"; ;
                    string CognexStdRoiPath = FileUtils.GetAppDirectory() + @"\DN\RunConfig_Std.ini";
                    CompareCognexRoiFunc(CognexRoiPath, CognexStdRoiPath , ref totalNgCount_Cognex);
                    #endregion

                    #region SPC Compare
                    string Stdroi_Spc = rootPath + "\\" + "SPC_Std.txt";
                    CompareSpcFunc(Stdroi_Spc, ref totalNgCount_Spc);
                    #endregion
                }
                else if (Common.ProjectName == "PostBottom")
                {
                    roiFilePath = rootPath + "\\" + "R2297_Post_Station_Vision_Bottom_ROI_New.txt";
                    roiFilePath_Std = rootPath + "\\ROI_Std" + "\\" + "R2297_Post_Station_Vision_Bottom_ROI_Std.txt";

                    CompareRoiFuc(roiFilePath, roiFilePath_Std, ref totalNgCount_Camera);
                    CompareRoiFuc(roi_7060, roi_7060_Std, ref totalNgCount_7060);
                }
                else if (Common.ProjectName == "PostBook")
                {
                    roiFilePath = rootPath + "\\" + "R2297_Post_Station_Vision_Book_ROI_New.txt";
                    roiFilePath_Std = rootPath + "\\ROI_Std" + "\\" + "R2297_Post_Station_Vision_Book_ROI_Std.txt";

                    CompareRoiFuc(roiFilePath, roiFilePath_Std, ref totalNgCount_Camera);
                    CompareRoiFuc(roi_7060, roi_7060_Std, ref totalNgCount_7060);
                }

                if (totalNgCount_Camera == 0 && totalNgCount_Cognex ==0 && totalNgCount_Spc == 0)
                {
                    Action<int, int, int ,string> DisplayUI = new Action<int, int, int , string>(UpdaUI);
                    DisplayUI(totalNgCount_Camera, totalNgCount_Cognex, totalNgCount_Spc, "OK");
                    ngDGV.Visible = false;
                }
                else
                {
                    Action<int, int, int, string> DisplayUI = new Action<int, int, int, string>(UpdaUI);
                    DisplayUI(totalNgCount_Camera, totalNgCount_Cognex, totalNgCount_Spc,"NG");
                }

                Thread.Sleep(5000);
            }
        }

        private void CompareRoiFuc(string RoiPath, string RoiPathStd, ref int totalNgCount)
        {
            DataRow dr = null;

            roiTable = FileUtils.OpenCSV(RoiPath);
            DataTable roiCopyTable = FileUtils.OpenCSV(RoiPathStd);

            totalNgCount = 0;

            if (roiCopyTable != null && roiCopyTable.Rows.Count > 0)
            {
                ngDt.Rows.Clear();
                for (int i = 0; i < roiCopyTable.Rows.Count; i++)
                {
                    string roiName = roiCopyTable.Rows[i]["ROI"].ToString();
                    string X = roiCopyTable.Rows[i]["X"].ToString();
                    string Y = roiCopyTable.Rows[i]["Y"].ToString();
                    string height = roiCopyTable.Rows[i]["长"].ToString();
                    string width = roiCopyTable.Rows[i]["宽"].ToString();
                    string filter = roiCopyTable.Rows[i]["过滤"].ToString();
                    string isShow = roiCopyTable.Rows[i]["是否显示"].ToString();
                    string isPointStyle = roiCopyTable.Rows[i]["点类型"].ToString();

                    for (int j = 0; j < roiTable.Rows.Count; j++)
                    {
                        int ngCount = 0;

                        if (roiTable.Rows[j]["ROI"].ToString().Equals(roiName))
                        {
                            if (!X.Equals(roiTable.Rows[j]["X"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!Y.Equals(roiTable.Rows[j]["Y"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!height.Equals(roiTable.Rows[j]["长"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!width.Equals(roiTable.Rows[j]["宽"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!filter.Equals(roiTable.Rows[j]["过滤"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!isShow.Equals(roiTable.Rows[j]["是否显示"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!isPointStyle.Equals(roiTable.Rows[j]["点类型"].ToString()))
                            {
                                ngCount++;
                            }
                        }
                        if (ngCount > 0)
                        {
                            dr = ngDt.NewRow();

                            dr[0] = "ROI_2D: " + roiName;

                            if (ngCount == 1)
                            {
                                dr[1] = "2D_ROI_X Compared Fail";
                            }
                            else if (ngCount == 2)
                            {
                                dr[1] = "2D_ROI_Y Value Compared Fail";
                            }
                            else if (ngCount == 3)
                            {
                                dr[1] = "2D_ROI_height Value Compared Fail";
                            }
                            else if (ngCount == 4)
                            {
                                dr[1] = "2D_ROI_width Value Compared Fail";
                            }
                            else if (ngCount == 5)
                            {
                                dr[1] = "2D_ROI_filterPoint Value Compared Fail";
                            }
                            else if (ngCount == 6)
                            {
                                dr[1] = "2D_ROI_IsDisplay Value Compared Fail";
                            }
                            else if (ngCount == 7)
                            {
                                dr[1] = "2D_ROI_SelectPointStyle Value Compared Fail";
                            }

                            ngDt.Rows.Add(dr);
                            totalNgCount++;
                        }
                    }
                }
            }
        }

        private void CompareCognexRoiFunc(string RoiPath, string RoiPathStd, ref int totalNgCount)
        {
            DataRow dr = null;

            //List<string> roiList3D = Get3DROIs(RoiPath);
            //List<string> roiList3D_Std = Get3DROIs(RoiPathStd);

            totalNgCount = 0;

        }


        private void CompareSpcFunc(string SpcPathStd, ref int totalNgCount_SPC)
        {
            DataRow dr = null;
            DataTable SpcTable = FileUtils.OpenCSV(SpcPathStd);
            DataTable UsingSpc = SQLiteUtils.GetSPC(Common.DatabaseName, "MeasureSize");

            totalNgCount_SPC = 0;

            if (SpcTable != null && SpcTable.Rows.Count > 0)
            {
                for (int i = 0; i < SpcTable.Rows.Count; i++)
                {
                    string roiName = SpcTable.Rows[i]["FAI"].ToString();
                    string Standard = SpcTable.Rows[i]["标准值"].ToString();
                    string Upper = SpcTable.Rows[i]["上偏差"].ToString();
                    string Lower = SpcTable.Rows[i]["下偏差"].ToString();

                    for (int j = 0; j < UsingSpc.Rows.Count; j++)
                    {
                        int ngCount = 0;

                        if (UsingSpc.Rows[j]["SizeName"].ToString().Equals(roiName))
                        {
                            if (!Standard.Equals(UsingSpc.Rows[j]["NormValue"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!Upper.Equals(UsingSpc.Rows[j]["UpperDeviation"].ToString()))
                            {
                                ngCount++;
                            }
                            else if (!Lower.Equals(UsingSpc.Rows[j]["LowerDeviation"].ToString()))
                            {
                                ngCount++;
                            }
                        }
                        if (ngCount > 0)
                        {                          
                            dr = ngDt.NewRow();

                            dr[0] = "SPC: " + roiName;

                            if (ngCount == 1)
                            {
                                dr[1] = "NormValue Compared Fail";
                            }
                            else if (ngCount == 2)
                            {
                                dr[1] = "UpperDeviation Value Compared Fail";
                            }
                            else if (ngCount == 3)
                            {
                                dr[1] = "LowerDeviation Value Compared Fail";
                            }

                            ngDt.Rows.Add(dr);
                            totalNgCount_SPC++;
                        }
                    }
                }
            }


        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            
        }


        private void ROIComapreForm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void UpdaUI(int count1, int count2 ,  int count3 ,string Status)
        {
            textBoxX2.Text = Convert.ToString(count1);
            textBoxX4.Text = Convert.ToString(count2);
            textBoxX6.Text = Convert.ToString(count3);
            labelX1.Text = Status;

            if (count1 == 0 && count2 == 0 && count3 == 0)  //000
            {
                textBoxX2.BackColor = Color.Green;
                textBoxX4.BackColor = Color.Green;
                textBoxX6.BackColor = Color.Green;
                labelX1.BackColor = Color.Green;
                buttonX1.Enabled = false;
                buttonX3.Enabled = false;
                buttonX4.Enabled = false;
            }
            if (count1 == 0 && count2 == 0 && count3 != 0)  //001
            {
                textBoxX2.BackColor = Color.Green;
                textBoxX4.BackColor = Color.Green;
                textBoxX6.BackColor = Color.Red;
                labelX1.BackColor = Color.Red;
                buttonX1.Enabled = false;
                buttonX3.Enabled = false;
                buttonX4.Enabled = true;
            }
            else if (count1 == 0 && count2 != 0 && count3 == 0) //010
            {
                textBoxX2.BackColor = Color.Green;
                textBoxX4.BackColor = Color.Red;
                textBoxX6.BackColor = Color.Green;
                labelX1.BackColor = Color.Red;
                buttonX1.Enabled = false;
                buttonX3.Enabled = true;
                buttonX4.Enabled = false;
            }
            else if (count1 == 0 && count2 != 0 && count3 != 0) //011
            {
                textBoxX2.BackColor = Color.Green;
                textBoxX4.BackColor = Color.Red;
                textBoxX6.BackColor = Color.Red;
                labelX1.BackColor = Color.Red;
                buttonX1.Enabled = false;
                buttonX3.Enabled = true;
                buttonX4.Enabled = true;
            }
            else if (count1 != 0 && count2 == 0 && count3 == 0) //100
            {
                textBoxX2.BackColor = Color.Red;
                textBoxX4.BackColor = Color.Green;
                textBoxX6.BackColor = Color.Green;

                labelX1.BackColor = Color.Red;
                buttonX1.Enabled = true;
                buttonX3.Enabled = false;
                buttonX4.Enabled = false;
            }
            else if (count1 != 0 && count2 == 0 && count3 != 0) //101
            {
                textBoxX2.BackColor = Color.Red;
                textBoxX4.BackColor = Color.Green;
                textBoxX6.BackColor = Color.Red;

                labelX1.BackColor = Color.Red;
                buttonX1.Enabled = true;
                buttonX3.Enabled = false;
                buttonX4.Enabled = true;
            }
            else if (count1 != 0 && count2 != 0 && count3 == 0) //110
            {
                textBoxX2.BackColor = Color.Red;
                textBoxX4.BackColor = Color.Red;
                labelX1.BackColor = Color.Green;
                buttonX1.Enabled = true;
                buttonX3.Enabled = true;
                buttonX4.Enabled = false;
            }
            else if (count1 != 0 && count2 != 0 && count3 != 0) //111
            {
                textBoxX2.BackColor = Color.Red;
                textBoxX4.BackColor = Color.Red;
                labelX1.BackColor = Color.Red;
                buttonX1.Enabled = true;
                buttonX3.Enabled = true;
                buttonX4.Enabled = true;
            }
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            Frm_CheckRoiRecord.Instance.ShowDialog(this);
        }

        private List<string> Get3DROIs(string filePath)
        {
            List<string> roiList = new List<string>();
            roiList = null;//VisionPro.iniFile.ReadSections(filePath, "Region");
            return roiList;
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            if (ngDt != null && ngDt.Rows.Count > 0)
            {
                ngDGV.Visible = true;
                ngDGV.DataSource = ngDt.DefaultView;
            }
            else
            {
                ngDGV.Rows.Clear();
                ngDGV.Visible = false;
            }
        }

        private void buttonX4_Click(object sender, EventArgs e)
        {
            if (ngDt != null && ngDt.Rows.Count > 0)
            {
                ngDGV.Visible = true;
                ngDGV.DataSource = ngDt.DefaultView;
            }
            else
            {
                ngDGV.Rows.Clear();
                ngDGV.Visible = false;
            }
        }

        private void ngDGV_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
    }
}
